import codecs
import sys
import os.path
import lxml.etree as ET
import png2obj.image
import png2obj.stardrive.hull

if len(sys.argv) < 2:
    print('Takes an image filename as an argument.')
else:
    filename = sys.argv[1]
    
    head, tail = os.path.split(filename)
    name, ext = os.path.splitext(tail)
    
    if len(sys.argv) >= 3:
        outfile = sys.argv[2]
    else:
        outfile = os.path.join(head, name + '.xml')

    imageData = png2obj.image.loadImage(filename)
    slots = png2obj.stardrive.hull.imageData2Slots(imageData, ("O", "I", "E"))
    numSlots = png2obj.stardrive.hull.countSlotRestrictionSets(slots)
    print("Slot counts: " + str(numSlots)) # empty, I, O, IO, E, IE, OE, IOE
    numAsy = png2obj.stardrive.hull.countAsymmetricalSlotPairs(slots)
    print('%s: %d asymmetrical slot pair(s)' % (name, numAsy))
    shipData = png2obj.stardrive.hull.defaultHullXML(slots, name)
    tree = ET.ElementTree(shipData)
    
    tree.write(outfile, xml_declaration=True, pretty_print=True, encoding='utf-8')
